/**
 * 公共方法提取
 */

const comMethods = {};

// 全局公共无图标toast info:传入的文字，time:显示时间
comMethods.toast = (info, time=1500) => {
	let msg = ''
	info ? msg = info : msg = '加载中...'
	uni.showToast({
		title: msg,
		icon: 'none',
		duration: time
	})
}

// 拆分图片选用第一张做产品/套餐封面
comMethods.imgSplit = list => {
	return list.split(',')[0]
}

// 排序 近到远
comMethods.sort = (data, key) => {
	return data.sort((a, b) => {
		var x = a[key];
		var y = b[key];
		if (x < y) { return 1 }
		if (x > y) { return -1 }
		return 0;
	});
}

// 日期转UNIX时间戳 -毫秒级
comMethods.timeStamp = (date, type) => {
	var time = ''
	type == 'start' ? time = '00:00:00' : time = '23:59:59';
	var str = date + ' ' + time;
	var ts  = new Date(str.replace(/-/g, "/")).getTime(); // ios不支持'-'连接的日期，将日期转换为 '/' 连接的
	var fmd = new Date(ts).toLocaleString();
	return ts
}

// 获取今天0 / 最近一周-7 / 最近一个月-30
comMethods.getDay = day => {
	var today = new Date();
	var targetday_milliseconds = today.getTime() + 1000*60*60*24*day;
	
	today.setTime(targetday_milliseconds);
	
	var tYear = today.getFullYear();
	var tMonth = today.getMonth();
	var tDate = today.getDate();
	
	tMonth = comMethods.doHandleMonth(tMonth + 1);
	tDate = comMethods.doHandleMonth(tDate);
	return tYear + "-" + tMonth + "-" + tDate;
}

comMethods.doHandleMonth = month => {
	var m = month;
	if (month.toString().length == 1) {
		m = "0" + month;
	}
	return m;
}

// 获取某年某月有多少天 - 可用获取上一月有多少天的筛选
comMethods.getMonthDay = (year, month) => {
	let days = new Date(year, month + 1, 0).getDate()
	return days
}

export default comMethods;
